/**
 * @author:linjiye
 * @date:2024/12/30
 * @desc:
 **/

import {Image, StyleSheet, Text, TouchableOpacity, View, Modal, TouchableHighlight, Clipboard} from 'react-native'
import React, {useEffect, useRef, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import FileTabBtn from "@/components/FileTabBtn";
import {Carousel, Toast, Flex} from "@ant-design/react-native";
import {useLocalSearchParams, useRouter} from "expo-router";
import FcModal from "@/components/FcModal";
import useApiOfSSE from "@/hooks/useApiOfSSE";
import {useDispatch, useSelector} from "react-redux";
import {
    useGetStreamWriting_by_templateMutation,
    useMmContentManagePubAddMutation,
    useSensitiveContentDetectionMutation
} from "@/store/api/aiOriginality/aiOriginalityApi";
import {useCopyFissionCombineMutation} from "@/store/api/explosiveFission/explosiveFissionApi";
import Animated, {
    interpolate,
    useAnimatedRef,
    useAnimatedStyle,
    useScrollViewOffset,
} from 'react-native-reanimated';
import {set_editData, set_result, set_SYZLParams} from "@/store/reducer/aiOriginality/aiOriginalitySlice";
import StreamWriterText from "@/components/StreamWriterText ";
import useGetStorage from "@/hooks/useGetStorage";
import Loading from "@/components/Loading";
import {set_params} from "@/store/reducer/morePlatforms/morePlatformsSlice";

type Props = {}

const result = (props: Props) => {
    const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
    const [list, setList] = useState([
        // {
        //     name: '1',
        //     id: 1,
        //     content: ''
        // }
        // , {
        //     name: '1',
        //     id: 2,
        //     content: ''
        // }
    ])
    const [carouselIndex, setCarouselIndex] = useState(0);
    const carouselRef = useRef<HTMLDivElement>(null);
    const [cpWay, setCpWay] = useState(false);
    const [isDetection, setIsDetection] = useState(false);
    const [params, setParams] = useState({})
    const [source, setSource] = useState(null)
    const [detectionData, setDetectionData] = useState([])
    const [isLoadings, setIsLoadings] = useState(false)
    const [desensitizationLoading, setDesensitizationLoading] = useState(false)
    
    const router = useRouter();
    const dispatch = useDispatch()

    const {fromWay} = useLocalSearchParams()

    // const token = useSelector(state => state.aiOriginality.token)

    // const SYZLParams = useSelector(state => state.aiOriginality.SYZLParams)

    const [addFun] = useMmContentManagePubAddMutation()
    const [sensitiveContentDetectionFun] = useSensitiveContentDetectionMutation()
    const [copyFissionCombineFun] = useCopyFissionCombineMutation()

    const [streamWriting_by_templateFun,{data, error, isLoading}] = useGetStreamWriting_by_templateMutation();
    console.log(data, error, isLoading);

    let params1 = useSelector(state => state.aiOriginality.params)
    let params2 = useSelector(state => state.aiOriginality.SYZLParams)
    let params3 = useSelector(state => state.aiInnovation.params)
    let params4 = useSelector(state => state.useExplosive.params)
    let params5 = useSelector(state => state.explosiveFission.params)
    let params6 = useSelector(state => state.morePlatforms.params)
    let editData = useSelector(state => state.aiOriginality.editData)

    useEffect(() => {
        let newList = list.map((item) => {
            if (item.id === editData.id) {
                return { ...item, content: editData.content };
            }
            return item;
        });
        setList(newList);
    }, [editData]);

    useEffect(() => {
        switch (fromWay) {
            case 'SdsrPage':
                setParams(params1)
                setItem(params1.articlesNum)
                break;
            case 'SYZLKPage':
                setParams(params2)
                setItem(params2.articlesNum)
                break;
            case 'aiInnovationPage':
                setParams(params3)
                setItem(params3.articlesNum)
                break;
            case 'useExplosivePage':
                setParams(params4)
                setItem(params4.articlesNum)
                break;
            case 'explosiveFissionPage':
                setParams(params5)
                setItem(params5.articlesNum)
                break;
            case 'morePlatformsPage':
                setParams(params6)
                setItem(params6.articlesNum)
                break;
        }



    }, [fromWay, params, params1, params2, params3, params4,params5])

    function setItem(num){
        let arr = []
        for (let i = 1; i <= num; i++){
            arr.push({
                name: '',
                id: i,
                content: ''
            })
        }
        setList(arr)

        setTimeout(()=>{
            handleRequery()
        },1000)
    }

    function handleRequery() {
        let num = params.articlesNum

        console.log(num);

        if (fromWay === 'explosiveFissionPage') {
            let url ='mm/aicreation/copy_fission_combine'
            let newParams = {
                start: params.aList,
                end: params.cList,
                middle: params.bList,
                num
            }
            if(num) getData3(url,newParams)
        } else {

            for (let i = 1; i <= num; i++) {
                if (fromWay === 'SYZLKPage') {
                    // getData1(i)
                    fetchStream({
                        index: i,
                        url: 'mm/aicreation/original_copywriting',
                        params: {
                            stream: true,
                            reqIndex: i,
                            ...params
                        }
                    })
                } else if (fromWay === 'SdsrPage') {
                    // getData(i)
                    fetchStream({
                        index: i,
                        url: 'mm/aicreation/writing_by_template',
                        params: {
                            templateId: '1749679210634153986',
                            vars: params.vars,
                            reqIndex: 1
                        }
                    })
                } else if (fromWay === 'aiInnovationPage' || fromWay === 'morePlatformsPage') {
                    let url = 'mm/aicreation/writing_on_explosive_case'
                    if (!params.groupId) url = 'mm/aicreation/writing_by_template'
                    // getData2(i, url)
                    fetchStream({
                        index: i,
                        url,
                        params: {
                            stream: true,
                            reqIndex: i,
                            ...params
                        }
                    })
                } else if (fromWay === 'useExplosivePage') {
                    let url = 'mm/aicreation/industry_explosive_writing'
                    // getData2(i, url)
                    fetchStream({
                        index: i,
                        url,
                        params: {
                            stream: true,
                            reqIndex: i,
                            ...params
                        }
                    })
                }
            }

        }
    }

    function requireAgain() {
        setCarouselIndex(0)
        setItem(params.articlesNum)
    }

    const getData =  (index: number) => {
        // console.log(index,'----------');
        // useApiOfSSE({
        //     url: 'mm/aicreation/writing_by_template',
        //     payload: {
        //         // stream: true,
        //         templateId: '1749679210634153986',
        //         vars: params.vars,
        //         reqIndex: index
        //     }
        // })
        //
        // await streamWriting_by_templateFun({
        //     stream: true,
        //             templateId: '1749679210634153986',
        //             vars: params.vars,
        //             reqIndex: index
        // }).then((e) => {
        //             let res = JSON.parse(e.data)
        //             // if (res.status == 'success') {
        //                 let txt = res.text.replace(/(<br\/>)|(<br)/g, '');
        //     let l = [...list]
        //                 l[index - 1].content = txt
        //                 setList(l)
        //             // }
        // })

        fetchStream(index)
    }

    async function fetchStream(val:any = {}) {
        setIsLoadings(true)
       await useGetStorage('token').then(async (token) => {
           try {
               const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}${val.url}`,{
                   method: 'POST',
                   headers: {
                       'content-type': 'application/json',
                       'x-access-token': token,
                   },
                   body: JSON.stringify(val.params)
               });
               const blob = await response.blob();
               const reader = new FileReader();

               reader.onload = (event) => {
                   const result = event.target.result;
                   // 按行分割流式数据
                   const lines = result.split('\n');
                   lines.forEach((line) => {
                       if (line) {
                           console.log(line);
                           let newLine = `${line.replace('data:','')}`;
                           // 在这里处理流式数据
                           let res = JSON.parse(newLine)
                           if (res.status == 'success') {
                               let txt = res.text.replace(/(<br\/>)|(<br)/g, '');
                               let l = [...list]
                               l[val.index - 1].content = txt
                               console.log(l);
                               setList(l)

                               if(res.stop) {
                                setIsLoadings(false)
                                }
                           } else {
                               if(res.stop) {
                                   Toast.info(res.message)
                               }
                           }
                       }
                   });
                   setIsLoadings(false)
               };

               reader.onerror = (error) => {
                   setIsLoadings(false)
                   console.error('Error reading blob:', error);
               };

               reader.readAsText(blob);
           } catch (error) {
               setIsLoadings(false)
               console.log('Error fetching stream:', error);
           }
        })
    }

    const getData3 = ( url: string,p) => {
        copyFissionCombineFun(p).then(({data: {code, result}}) => {
            if (code === 200) {
                let l = [...list]
                l.map((item, index) => {
                    item.content = result[index]
                })
                setList(l)
            }
        })
    }


    // @ts-ignore
    function getScrollBodyInfo({height}) {
        setPageScrollBodyH(height)
    }

    const handleCarouselItemChange = (val: React.SetStateAction<number>) => {
        setCarouselIndex(val)
    }

    function handleClickSub() {
        let i = carouselIndex - 1
        carouselRef.current.goTo(i)
        setCarouselIndex(i)
    }

    function handleClickAdd() {
        let i = carouselIndex + 1
        carouselRef.current.goTo(i)
        setCarouselIndex(i)
    }

    function handleToEdit(item) {
        dispatch(set_editData(item))
        router.navigate('/aiOriginality/edit')
    }

    function handleTextComparison() {
        dispatch(set_result(list))
        router.navigate('/aiOriginality/textComparison')
    }

    function handleAdd() {
        let params = {
            content: list[carouselIndex].content,
            templateId: "1749679210634153986",
            title: null
        }
        addFun(params).then(({data: {code, result}}) => {
            if (code === 200) Toast.info(result)
        })
    }

    async function handleCopyToClipboardComponent() {
        try {
            await Clipboard.setString(list[carouselIndex].content);
            Toast.info('复制成功')
        } catch (error) {
            console.log(error)
            Toast.info('复制失败')
        }
    }

    function handleSensitiveContentDetection() {
        let params = {
            saveResult: false,
            targetId: '',
            text: list[carouselIndex]?.content
        }

        setDesensitizationLoading(true)

        sensitiveContentDetectionFun(params).then(({data: {code, result}}) => {
            if (code === 200) {
                setIsDetection(true)
                setDetectionData(result)
            }
            setDesensitizationLoading(false)
        })
    }

    return (
        <PageScrollView
            isTransparentTab
            getPageScrollBodyInfo={getScrollBodyInfo}
            bodyStyle={{paddingBottom: 0,marginTop: 0}}
            pageTab={
                <PageTabBar
                    style={{marginVertical: 10}}
                    title={`生成结果${carouselIndex+1}/${list.length}`}
                    left={
                        <TouchableOpacity style={{position: "relative",zIndex: 10000}} onPress={() => router.replace('/(tabs)')} style={{paddingHorizontal: 5,marginHorizontal: 5}}>
                            <Text style={{fontFamily: 'FcIconFont', fontSize: 24, color: 'rgba(0,0,0,0.9)'}}>&#xe66a;</Text>
                        </TouchableOpacity>
                    }
                    right={
                        <TouchableOpacity style={styles.sc_btn} onPress={() => requireAgain()}>
                            <Text style={styles.sc_btn_txt}>再次生成</Text>
                        </TouchableOpacity>
                    }
                />
            }
            pageBottom={
                <View>
                    <View style={styles.bottom_btn}>
                        <View style={{flex: 1, marginRight: 4}}>
                            <FcButton
                                type='default'
                                onClick={() => handleTextComparison()}
                                style={{
                                    width: '100%',
                                    height: 40,
                                    justifyContent: 'center',
                                    backgroundColor: '#F1F2F4',
                                    borderRadius: 8
                                }}
                                itemStyle={{fontSize: 15}}
                                textName='查看文案相似度对比'/>
                        </View>
                        <View style={{flex: 1, marginLeft: 4}}>
                            <FcButton
                                type='BjJB'
                                onClick={() => setCpWay(true)}
                                colors={['#6989FF', '#C65EFD']}
                                style={{width: '100%', height: 40, justifyContent: 'center'}}
                                itemStyle={{borderRadius: 8, fontSize: 15}}
                                textName='AI 成片'/>
                        </View>
                    </View>
                </View>
            }
        >
            <View style={[styles.body_wrap, {height: pageScrollBodyH - 10}]}>
                <View style={styles.header_wrap}>
                    <Text style={{fontSize: 12,color: 'rgba(0, 0, 0, 0.5)'}}>第{carouselIndex+1}篇 默认式</Text>
                    <FileTabBtn index={carouselIndex} len={list.length} onClickSub={handleClickSub}
                                onClickAdd={handleClickAdd}/>
                </View>
                <View style={styles.content_wrap}>
                    <Carousel
                        ref={carouselRef}
                        style={styles.carousel_wrap}
                        selectedIndex={carouselIndex}
                        dots={false}
                        afterChange={handleCarouselItemChange}
                    >
                        {list.map((item, index) => (
                            <>
                                {!item.content && isLoadings && <Loading key={index}/>}
                                {item.content && !isLoadings &&
                                    <Animated.ScrollView key={index}>
                                        <TouchableOpacity onPress={() => handleToEdit(item)}>
                                            <View
                                                style={styles.item_wrap}>
                                                <Text style={styles.item}>{item.content}</Text>
                                                {/*<StreamWriterText chunks={data}/>*/}
                                            </View>
                                        </TouchableOpacity>
                                    </Animated.ScrollView>
                                }
                            </>
                        ))}
                    </Carousel>
                </View>
                <View style={styles.btn_wrap}>
                    <TouchableOpacity style={styles.btn} onPress={() => handleAdd()}>
                        <Text style={{fontFamily: 'FcIconFont', color: '#181818', fontSize: 16}}>&#xe631;</Text>
                        <Text style={{color: 'rgba(0, 0, 0, 0.9)', fontSize: 12}}>导入内容管理</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.btn} onPress={() => handleCopyToClipboardComponent()}>
                        <Text style={{fontFamily: 'FcIconFont', color: '#181818', fontSize: 16}}>&#xe65e;</Text>
                        <Text style={{color: 'rgba(0, 0, 0, 0.9)', fontSize: 12}}>复制</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.btn} onPress={() => handleSensitiveContentDetection()}>
                        <Text style={{fontFamily: 'FcIconFont', color: '#181818', fontSize: 16}}>&#xe607;</Text>
                        <Text style={{color: 'rgba(0, 0, 0, 0.9)', fontSize: 12}}>内容脱敏检测</Text>
                    </TouchableOpacity>
                    {/*<View>*/}
                    {/*    <FcButton*/}
                    {/*        type='txtJBAndBjJB'*/}
                    {/*        onClick={() => handleSensitiveContentDetection()}*/}
                    {/*        colors={['rgba(105, 137, 255, 0.2)', 'rgba(198, 94, 253, 0.2)']}*/}
                    {/*        style={{width: 150, height: 28, justifyContent: 'center'}}*/}
                    {/*        itemStyle={{height: 28, borderRadius: 8,paddingTop:4}}*/}
                    {/*        textName='内容脱敏检测' fontSize={12}></FcButton>*/}
                    {/*</View>*/}
                </View>
            </View>

            <FcModal
                isOpen={cpWay}
                onFcModalClose={() => setCpWay(false)}
                titleText='选择成片方式'
            >
                <View style={{paddingBottom: 18}}>
                    <TouchableOpacity>
                        <View style={styles.cp_wrap}>
                            <View style={styles.cp_left}>
                                <Image style={styles.cp_icon}
                                       source={require('@/assets/images/aiOriginality/bd_cp_icon.png')}
                                       resizeMode={"contain"}></Image>
                                <Text style={styles.cp_title}>本地成片</Text>
                            </View>
                            <Text style={styles.cp_right}>&#xe609;</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity>
                        <View style={styles.cp_wrap}>
                            <View style={styles.cp_left}>
                                <Image style={styles.cp_icon}
                                       source={require('@/assets/images/aiOriginality/yd_cp_icon.png')}
                                       resizeMode={"contain"}></Image>
                                <Text style={styles.cp_title}>云端成片</Text>
                            </View>
                            <Text style={styles.cp_right}>&#xe609;</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity>
                        <View style={styles.cp_wrap}>
                            <View style={styles.cp_left}>
                                <Image style={styles.cp_icon}
                                       source={require('@/assets/images/aiOriginality/szr_cp_icon.png')}
                                       resizeMode={"contain"}></Image>
                                <Text style={styles.cp_title}>数字人成片</Text>
                            </View>
                            <Text style={styles.cp_right}>&#xe609;</Text>
                        </View>
                    </TouchableOpacity>
                    <TouchableOpacity>
                        <View style={styles.cp_wrap}>
                            <View style={styles.cp_left}>
                                <Image style={styles.cp_icon}
                                       source={require('@/assets/images/aiOriginality/sy_cp_icon.png')}
                                       resizeMode={"contain"}></Image>
                                <Text style={styles.cp_title}>数字声音成片</Text>
                            </View>
                            <Text style={styles.cp_right}>&#xe609;</Text>
                        </View>
                    </TouchableOpacity>
                </View>
            </FcModal>
            <FcModal
                isOpen={isDetection}
                onFcModalClose={() => setIsDetection(false)}
                titleText={'内容脱敏检测'}
                titleBottomBorderWidth={0}
                style={{height: 'auto', paddingHorizontal: 16}}
                bottom={
                    <Flex justify='between' style={{height: 56}}>
                        <FcButton
                            onPress={() => setIsDetection(false)}
                            type='default'
                            style={{width: '48%', height: 40, backgroundColor: '#F1F2F4', borderRadius: 8}}
                            itemStyle={{borderRadius: 8, fontSize: 15}}
                            textName='返回修改文案'
                            borderWidth={0}
                        ></FcButton>

                        <FcButton
                            onClick={() => {setIsDetection(false); setCpWay(true)}}
                            type='BjJB'
                            colors={['#6989FF', '#C65EFD']}
                            style={{width: '48%', height: 40}}
                            itemStyle={{borderRadius: 8, fontSize: 15}}
                            textName='继续AI成片'
                        />
                    </Flex>
                }
            >
                <View style={{paddingBottom: 10}}>
                    {detectionData.sensitive &&
                        <Text style={styles.check_md}>
                            <Text style={styles.check_md_txt}>脱敏检测目的：</Text>
                            敏感词汇可能造成曝光了减少 、平台下架、用户投诉、版权纠纷、法律风险，请认真对待敏感内容检测结果，并对内容进行改善
                        </Text>
                    }
                    {!detectionData.sensitive &&
                        <Flex direction='column' justify='center' style={[styles.check_hint, {height: 300}]}>
                            <Image style={{width: 126, height: 126}} source={require('@/assets/images/public/no_detection1.png')}></Image>
                            <Text style={[styles.check_hint_txt, {color: 'rgba(0, 0, 0, 0.5)'}]}>没有发现违规风险！</Text>
                        </Flex>
                    }

                    {detectionData.sensitive &&
                        <>
                            <View style={styles.check_hint}>
                                <Text style={styles.check_hint_txt}>{detectionData.riskAndAdviceSummary}</Text>
                            </View>
                            {detectionData?.sensitiveDetail?.map((item, index) =>
                                <View style={styles.check_hint} key={index}>
                                    <Text style={styles.check_hint_txt}>{index + 1}.** <Text
                                        style={{color: '#FA5151'}}>{item.keyword}</Text>**</Text>
                                    <Text
                                        style={styles.check_hint_txt}>**建议改进**：{item.advice}</Text>
                                </View>
                            )}
                        </>
                    }
                    <Text style={styles.detection_desc}>-- 预警提示，仅供参考 --</Text>
                </View>
            </FcModal>
            {
                desensitizationLoading && 
                <Flex direction='column' justify='center' style={styles.desensitization_box}>
                    <Image style={{width: 70, height: 70}} source={require('@/assets/images/gif/desensitization.gif')}></Image>
                    <Text style={{color: '#FFF', marginTop: 5}}>脱敏检测中...</Text>
                </Flex>
            }
            
        </PageScrollView>
    )
}

export default result

const styles = StyleSheet.create({
    sc_btn: {
        width: 64,
        height: 28,
        display: 'flex',
        justifyContent: "center",
        alignItems: "center",

        borderRadius: 8,
        backgroundColor: 'white'
    },
    sc_btn_txt: {
        fontSize: 12,
        color: '#2856FF',
    },

    body_wrap: {
        height: '100%',
        backgroundColor: 'white',
        flexDirection: 'column',
        justifyContent: "space-between",
        borderRadius: 8
    },

    header_wrap: {
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: 'space-between',
        paddingHorizontal: 16,
        paddingVertical: 10
    },
    bottom_btn: {
        flexDirection: "row",
        alignItems: "center",
        paddingHorizontal: 16,
        height: 56,
        justifyContent: "space-between",
        backgroundColor: 'white'
    },

    btn_wrap: {
        flexDirection: "row",
        alignItems: "center",
        padding: 12,
        backgroundColor: 'white',
        marginBottom: 8,
        borderTopWidth: 0.5,
        borderTopColor: 'rgba(0, 0, 0, 0.1)',
    },
    btn: {
        flexDirection: "row",
        alignItems: "center",
        backgroundColor: '#F1F2F4',
        borderRadius: 8,
        paddingHorizontal: 8,
        height: 28,
        marginRight: 8
    },
    content_wrap: {
        flex: 1,
    },
    carousel_wrap: {
        width: '100%',
        height: '100%'
    },
    item_wrap: {
        paddingHorizontal: 12,
        paddingVertical: 10
    },
    item: {
        color: 'rgba(0, 0, 0, 0.9)',
        fontSize: 17,
        lineHeight: 26
    },
    cp_wrap: {
        marginHorizontal: 32,
        marginTop: 16,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        height: 48,
        paddingHorizontal: 18,
        backgroundColor: '#F7F8FA',
        borderRadius: 8,
    },
    cp_left: {
        flexDirection: "row",
        alignItems: "center",
    },
    cp_right: {
        fontFamily: 'FcIconFont',
        color: '#a3a4a5',
        fontSize: 16,
    },
    cp_icon: {
        width: 32,
        height: 32,
        marginRight: 12,
    },
    cp_title: {
        fontSize: 15,
        color: 'rgba(0, 0, 0, 0.9)'
    },
    footer_wrap: {
        flexDirection: "row",
        alignItems: "center",
        height: 56,
        borderTopWidth: 0.5,
        borderTopColor: 'rgba(0, 0, 0, 0.1)',
        padding: 0
    },
    footer_btn: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center"
    },
    popupSlideDown: {
        padding: 0
    },

    content: {
        padding: 20,
        alignItems: 'center',
    },

    modal_default: {
        width: 280,
        borderBottomRightRadius: 12,
        borderBottomLeftRadius: 12
    },
    check_md: {
        paddingHorizontal: 11,
        paddingVertical: 12,
        borderRadius: 8,
        color: 'rgba(0,0,0,0.9)',
        backgroundColor: '#F1F2F4',
        marginTop: 15,
        lineHeight: 18,
        fontSize: 12
    },
    check_md_txt: {
        color: '#FA5151'
    },
    check_hint: {
        marginTop: 12,
    },
    check_hint_txt: {
        lineHeight: 24,
        fontSize: 15,
        color: 'rgba(0,0,0,0.9)',
    },
    desensitization_box: {
        position: 'absolute',
        top: '50%',
        left: '50%',
        width: 136,
        height: 141,
        borderRadius: 8,
        transform: 'translate(-50%, -50%)',
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
    },
    detection_desc: {
        color: 'rgba(0, 0, 0, 0.2)',
        fontSize: 10,
        textAlign: 'center',
        marginTop: 30,
    }
})